//
//  YWAssignTroubleMissionTableViewController.m
//  maintain
//
//  Created by 烟雨云渊 on 17/1/13.
//  Copyright © 2017年 ewin. All rights reserved.
//

#import "YWAssignTroubleMissionTableViewController.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "MJRefresh.h"
#import "Masonry.h"
#import "UIColor+CustomColors.h"
#import "UIScrollView+EmptyDataSet.h"
#import "YWCirculationInfo.h"
#import "YWCirculationManager.h"
#import "YWCommonTool.h"
#import "YWMacro.h"
#import "YWMission.h"
#import "WMHttpTool.h"
#import "MJExtension.h"

#import "YWPostTroubleBillCell.h"
#import "YWWriteNoteCell.h"

#import "YWHandler.h"
#import "YWBuilding.h"
#import "MBProgressHUD.h"
#import "YWConst.h"
#import "YWEwinManager.h"
#import "YWLoginUser.h"
#import "YWLoginTool.h"
#import "UIView+Extension.h"

#import "YWNotifyManager.h"
#import "YWMissionManager.h"
#import "YWReplyManager.h"
#import "YWTroubleReplyTableViewController.h"
#import "YWSelectContactTableViewController.h"
#import "YWReportTroubleModel.h"
#import "YWTroubleMissionModel.h"
#import "YWTroubleMissionManager.h"
#import "YWReportTroubleManager.h"

static CGFloat const kMargin = 15;
static CGFloat const kGap = 15;
static CGFloat const kLabelWidth = 70;
static CGFloat const kLabelHeight = 40;

static CGFloat const kDatePickerViewH = 216;

#define kButtonWidth SCREEN_WIDTH-kMargin*3-kLabelWidth
#define KNoteTextMax 100

@interface YWAssignTroubleMissionTableViewController ()<YWWriteNoteCellDelegate,UIAlertViewDelegate,YWPostTroubleBillCellDelegate,UITextViewDelegate,YWContactVCSelectContactDelegate>{
    NSString *startDate;
    NSString *assignNote;
    UIWebView *phoneCallWebView;
}
@property (nonatomic, strong) UILabel *tableHeadLabel;
@property (nonatomic, weak) MBProgressHUD* HUD;

//有关分配任务布局
@property (nonatomic, strong) UIView * footView;

@property (nonatomic, strong) UIButton *sureButton;

@property (nonatomic, strong) UIDatePicker *datePicker;

@property (nonatomic, assign) BOOL isShowDatePicker;

@property (nonatomic, strong) YWHandler *handler;

@end

@implementation YWAssignTroubleMissionTableViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = NSLocalizedString(@"assignMission", nil);//@"分配任务";
    
    [self setupDatePicker];
    [self setupTableView];
}

- (void)setupDatePicker{
    NSString *string = [YWCommonTool showDate:[[NSDate date] timeIntervalSince1970]];
    startDate = string;
    [self.datePicker setFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, kDatePickerViewH)];
    _isShowDatePicker = NO;
}

- (void)setupTableView{
    [self.tableView registerClass:[YWPostTroubleBillCell class] forCellReuseIdentifier:YWPostTroubleBillCellIdentifier];
    [self.tableView registerClass:[YWWriteNoteCell class] forCellReuseIdentifier:YWWriteNoteCellIdentifier];
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.separatorColor = [UIColor whiteColor];
    self.tableView.tableHeaderView = self.tableHeadLabel;
    self.tableView.tableFooterView = self.footView;
    self.tableView.estimatedRowHeight = 44.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
}

#pragma mark - UITableViewDataSource mothods
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    return section == 0 ? 1 : 3;
}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    //没有流转信息
    if (indexPath.section == 0) {
        YWPostTroubleBillCell* cell = [tableView dequeueReusableCellWithIdentifier:YWPostTroubleBillCellIdentifier];
        [self configurePostTroubleBillCell:cell atIndexPath:indexPath];
        return cell;
    }else{
        static NSString *cellIdentifier = @"YWAssignTroubleMissionTableViewControllerCellIdentifier";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.textLabel.font = kContentFont;
            cell.detailTextLabel.font = kContentFont;
        }
        if (indexPath.row == 0) {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            if (_handler) {
                cell.textLabel.text = [NSString stringWithFormat:@"%@ %@",NSLocalizedString(@"executor", nil),_handler.userName?:@""];//执行人
            }else{
                cell.textLabel.text = [NSString stringWithFormat:@"%@ %@",NSLocalizedString(@"executor", nil),NSLocalizedString(@"pleaseSelectExecutor", nil)]; //@"执行人: 请选择执行人";
            }
            return cell;
        }else if (indexPath.row == 1){
            cell.textLabel.text = [NSString stringWithFormat:@"截止日期: %@",startDate?:NSLocalizedString(@"pleaseSelect", nil)];//请选择
            return cell;
        }else{
            YWWriteNoteCell * cell = [tableView dequeueReusableCellWithIdentifier:YWWriteNoteCellIdentifier];
            cell.delegate = self;
            return cell;
        }
    }
}

#pragma configure cell
- (void)configurePostTroubleBillCell:(YWPostTroubleBillCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = NO;
    cell.delegate = self;
    cell.reportTrouble = self.troubleMissionModel.trouble;
}

#pragma mark - UITableViewDataDelegate mothods
- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
    if (indexPath.section == 0) {
        return UITableViewAutomaticDimension;
//        [tableView fd_heightForCellWithIdentifier:YWPostTroubleBillCellIdentifier cacheByIndexPath:indexPath configuration:^(YWPostTroubleBillCell *cell) {
//            [self configurePostTroubleBillCell:cell atIndexPath:indexPath];
//        }];
    }else{
        return indexPath.row !=2 ?44:90;
    }
}


#pragma mark - 有关section头部和尾部的布局
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return  section == 0 ? 10 : 1;
}

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            YWSelectContactTableViewController *contactVC = [[YWSelectContactTableViewController alloc] init];
            contactVC.delegate = self;
            contactVC.buildingId = self.troubleMissionModel.trouble.building.buildingId;
            contactVC.isMultiSelect = NO;
            contactVC.ownContacts = _handler ? @[_handler] : nil;
            contactVC.titleName = NSLocalizedString(@"selectExecutor", nil);//@"选择执行人";
            [self.navigationController pushViewController:contactVC animated:YES];
        }else if (indexPath.row == 1){
            [self.view endEditing:YES];

//            CGFloat offsetY = self.tableView.contentSize.height -self.tableView.bounds.size.height+kGap*2+kMargin;
//            if (offsetY>=0) {
//                [self.tableView setContentOffset:CGPointMake(0, offsetY) animated:YES];
//            }
            
            _isShowDatePicker = YES;
            [UIView animateWithDuration:0.25 animations:^{
                self.datePicker.frame=CGRectMake(0, SCREEN_HEIGHT-216, SCREEN_WIDTH, 216);
            }];
        }
    }
}

#pragma mark - YWWriteNoteCellDelegate
- (void)passNote:(NSString*)note{
    assignNote = note;
}

- (void)clickPostTroubleMobileWithNumber:(NSString *)mobileNumber{
    if (mobileNumber.length) {
        NSURL *phoneURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",mobileNumber]];
        if ( !phoneCallWebView ) {
            phoneCallWebView = [[UIWebView alloc] initWithFrame:CGRectZero];// 这个webView只是一个后台的 不需要add到页面上来  效果跟方法二一样 但是这个方法是合法的
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [phoneCallWebView loadRequest:[NSURLRequest requestWithURL:phoneURL]];
        });
    }else{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:NSLocalizedString(@"noHaveContactTelphoneNumble", nil) preferredStyle:UIAlertControllerStyleAlert];//@"没有此联系人的电话号码"
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:cancel];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

-(UILabel *)tableHeadLabel{
    if (!_tableHeadLabel) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
        label.font = KTitleFont;
        label.textAlignment = NSTextAlignmentCenter;
        label.backgroundColor = [UIColor whiteColor];
        label.attributedText = [YWCommonTool labelAttributedStringWithFristStr:NSLocalizedString(@"codeFormatter", nil) secondStr:self.troubleMissionModel.trouble.troubleSequence?:@"无" secondColor:[UIColor customYellowColor]];
        _tableHeadLabel = label;
    }
    return _tableHeadLabel;
}

- (MBProgressHUD*)HUD
{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:self.tableView];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = NSLocalizedString(kTextBeingProcessed, nil);
        hud.dimBackground = YES;
        //hud.animationType = MBProgressHUDAnimationZoom;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.view addSubview:hud];
    }
    return _HUD;
}


- (UIView*)footView{
    if (!_footView) {
        UIView * footTableView = [[UIView alloc] init];
        footTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, kLabelHeight+kGap*2);
        footTableView.backgroundColor = [UIColor customBackgroudColor];
        footTableView.userInteractionEnabled = YES;
        _footView = footTableView;
        [_footView addSubview:self.sureButton];
    }
    return _footView;
}

-(UIDatePicker *)datePicker{
    if (!_datePicker) {
        _datePicker=[[UIDatePicker alloc]init];
        [_datePicker setBackgroundColor:[UIColor whiteColor]];
        _datePicker.datePickerMode = UIDatePickerModeDate;
        _datePicker.locale =[NSLocale localeWithLocaleIdentifier:@"zh"];
        [_datePicker setMinimumDate:[NSDate date]];
        [_datePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
        [self.navigationController.view addSubview:_datePicker];
    }
    return _datePicker;
}

-(UIButton *)sureButton{
    if (!_sureButton) {
        UIButton* sureButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [sureButton setFrame:CGRectMake(kMargin, kGap, kLabelWidth+kMargin+kButtonWidth, kLabelHeight)];
        [sureButton setTitle:NSLocalizedString(@"sure", nil) forState:UIControlStateNormal];
        [sureButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [sureButton setBackgroundColor:[UIColor customBlueColor]];
        sureButton.titleLabel.font = kContentFont;
        sureButton.layer.borderColor = [UIColor customBlueColor].CGColor;
        sureButton.layer.borderWidth = 1.0;
        sureButton.layer.masksToBounds = YES;
        sureButton.layer.cornerRadius = 4.0;
        [sureButton addTarget:self action:@selector(clickSureButton) forControlEvents:UIControlEventTouchUpInside];
        [self.footView addSubview:sureButton];
        _sureButton = sureButton;
    }
    return _sureButton;
}

#pragma mark - privateMeth
-(void)resetDatePicker{
    _isShowDatePicker = NO;
    [UIView animateWithDuration:0.25 animations:^{
        [_datePicker setFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, kDatePickerViewH)];
    }];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
    if (_isShowDatePicker) {
        [self resetDatePicker];
    }
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self resetDatePicker];
}

#pragma mark - YWContactVCSelectContactDelegate
-(void)selectSingleContact:(YWHandler *)contact{
    _handler = contact;
    [self.tableView reloadData];
}

-(void)handleDateButtonEvent{
    [self.tableView endEditing:YES];
    _isShowDatePicker = YES;
    [UIView animateWithDuration:0.25 animations:^{
        self.datePicker.frame=CGRectMake(0, SCREEN_HEIGHT-64-kDatePickerViewH, SCREEN_WIDTH, kDatePickerViewH);
    }];
}

-(void)dateChanged:(id)sender{
    UIDatePicker *picker = (UIDatePicker*)sender;
    NSDate *date = picker.date;
    
    NSString *format =  KTimeFormatDate;
    NSString *string = [YWCommonTool showTime:[date timeIntervalSince1970] andFormatter:format];
    startDate = string;
    [self.tableView reloadData];
}

-(void)clickSureButton{
    [self.tableView endEditing:YES];
    [self resetDatePicker];
    if (!_handler) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"pleaseSelectExecutor", nil)];//@"请选择执行人"
        return;
    }
    if ([YWCommonTool isContainsEmoji:assignNote]) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return;
    }
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"makeSureToAssignMission", nil) message:nil preferredStyle:UIAlertControllerStyleAlert];//@"确认分配任务"
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSString *string = [NSString stringWithFormat:@"%@ 00:00:00",startDate];
        NSTimeInterval timeInterval = [YWCommonTool timeIntervalWithDatestring:string dateFormatter:KTimeFormatFullDateAndTime] * 1000;
        [self passHandler:_handler finishDate:timeInterval note:assignNote];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)passHandler:(YWHandler*)handler finishDate:(NSTimeInterval)finishDate note:(NSString*)note
{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {return;}
    
    NSDictionary* params = @{ @"troubleId" : @(_troubleMissionModel.trouble.troubleId),
                              @"handlerId" : @(handler.uniqueId),
                              @"cutoffTime" : @(finishDate),
                              @"demand" : note ?: @"" };
    YWLog(@"%@",params);
    YWWeakSelf(weakSelf)
    [self.HUD show:YES];
    [[WMHttpTool shareHttpTool] postWithUrl:[YWCommonTool getDesignTroubleUrl] params:params success:^(NSHTTPURLResponse* response, id json) {
        [weakSelf.HUD hide:YES];
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextAssignSuccess, nil)];

//        YWTroubleMissionModelJson* troubleMissionJson = [YWTroubleMissionModelJson mj_objectWithKeyValues:json];
//        YWTroubleMissionModelApiJson * troubleJson = [YWTroubleMissionModelApiJson mj_objectWithKeyValues:json];
//        if (reportTrouble) {
//            //保存流转信息
//            [[YWCirculationManager shareManager] updateCirculationInfoWithArray:reportTrouble.circulationInfos];
//        }
        _troubleMissionModel.demand = note;
        _troubleMissionModel.cutoffTime = finishDate;
        _troubleMissionModel.executor = handler;
        YWHandler *creator = [[YWHandler alloc] init];
        YWLoginUser *currentUser = [YWLoginTool loginUser];
        creator.uniqueId = currentUser.uniqueId;
        creator.userName = currentUser.userName;
        creator.headIcon = currentUser.headIcon;
        creator.mobile = currentUser.mobile;
        _troubleMissionModel.creator = creator;
        _troubleMissionModel.troubleStatus = YWTroubleMissionStatusAssign;
        _troubleMissionModel.updateTime = [[NSDate date] timeIntervalSince1970] * 1000;
        //更新流转信息
        [[YWCirculationManager shareManager] createAndSaveLocalCirculationInfoWithType:YWCirculationInfoTypeAssignTroubleMission troubleId:_troubleMissionModel.trouble.troubleId recipient:handler note:note];
        //更新报障单状态
        [[YWReportTroubleManager shareManager] updateReportTroubleStatus:YWTroubleMissionStatusAssign troubleId:_troubleMissionModel.trouble.troubleId];
        //更新维修任务模型
        BOOL saveMission = [[YWTroubleMissionManager shareManager] updateTroubleMissionWithArray:_troubleMissionModel?@[_troubleMissionModel]:nil needUpdateReportTrouble:NO];
        [[YWEwinManager shareManager] subtractTotalCountWithType:YWUnReadCountTypeTrouble];
        if (saveMission) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:KPostRefreshCirculationDetailVCNoti object:nil];
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
        
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
        [self.HUD hide:YES];
        NSString *tips = nil;
        NSInteger statusCode = response.statusCode;
        if (statusCode == 406 || statusCode == 304) {
            [[YWCirculationManager shareManager] requestCirculationInfoWithTroubleId:weakSelf.troubleMissionModel.trouble.troubleId needTip:NO WithComplete:nil];
        }
        
        if (statusCode == 406) {
            tips = NSLocalizedString(kTextPendingTroubleFail, nil);//kTextPendingTroubleFail;
        }else if (statusCode == 304){
            tips = [NSString stringWithFormat:@"此%@已%@完成",NSLocalizedString(@"postTrouble", nil),NSLocalizedString(@"trouble", nil)];//@"此报障已维修完成";
        }else{
            tips = NSLocalizedString(@"kTextAssignFailed", nil);//@"分配失败,请稍后再试";
        }
        UIAlertController* alertController= [UIAlertController alertControllerWithTitle:tips message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"返回" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [[NSNotificationCenter defaultCenter] postNotificationName:KPostRefreshCirculationDetailVCNoti object:nil];
            [self.navigationController popViewControllerAnimated:YES];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }];
}

#pragma mark - UIKeyboardNSNotification
- (void)keyboardWillShow:(NSNotification*)notification
{
    [self resetDatePicker];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    //键盘弹起的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
